<?php
namespace Twoir\System\Support;

/**
 * 单个表处理方式 集合方法
 *
 * cighsen02 qq 365182575
 * 2023.09.02
 * update: 2024.05.03
*/
trait SingleTrait
{
	//新增时id
	protected static $lastid;

	/**
	 * 获得当前表名 2024.04.28增加 解决评论表选择问题
	 *
	 * @return string
	*/
	public static function getTable()
	{
		return property_exists(static::class, 'restb') ? static::TABLE . static::$restb : static::TABLE;
	}

    /**
     * 字段默认值类型
     *
     * @return array
    */
    public static function fieldType()
    {
        $default = static::MYDEFAULT;

        array_walk($default, function(&$value, $key){

            $value = is_null($value) || 0 === $value ? 'int' : 'string';

        });

        return $default;
    }

    /**
	 * 数量统计
	 * @param array
	 * @return int
	 */
	public static function getCount($where = [])
	{
		global $empire, $dbtbpre;

		$str_where = static::parseWhere($where, false)['where'];

		$sql = sprintf("SELECT count(*) as total FROM %s%s", $dbtbpre . static::getTable(), $str_where);

		//是否有记录
		return (int)$empire->gettotal($sql);
	}

	/**
	 * 读取当条信息
	 *
	 * @param array $where  条件
	 * @param array $field 调取的字段
     * @param string $groupby
	 * @param string $orderby
	 * @return array
	 */
	public static function getOne($where = [], $field = ['*'], $groupby = '', $orderby = '')
	{
	    $res = static::getList($where, $field, $groupby, $orderby, 1, 0, 0);

	    return $res ? $res[0] : [];
	}

	/**
	 * 读取多条(列表)
     *
	 * @param array $where  条件
	 * @param array $field 调取的字段
     * @param string $groupby
	 * @param string $orderby
	 * @param int $limit
	 * @param int $pagesize
     * @param int $page
	 * @return array
	 */
	 public static function getList($where = [], $field = ['*'], $groupby = '', $orderby = '', $limit = 0, $pagesize = 10, $page = 0)
	 {
        global $empire, $dbtbpre;

        $str_where = static::parseWhere($where, false)['where'];

		$res 		= [];
        $get_field  = ['*'] === $field ? static::FIELD : array_intersect(static::FIELD, $field);

        $sql = sprintf("SELECT %s FROM %s%s%s%s%s",
			'`' . implode('`,`', $get_field) . '`',
			$dbtbpre . static::getTable(),
			$str_where,
			null === $groupby || '' === $groupby ? '' : ' GROUP BY ' . $groupby,
			null === $orderby || '' === $orderby ? '' : ' ORDER BY ' . $orderby,
			0 === $limit && 0 === $pagesize ? '' : ($limit > 0 ? ' LIMIT ' . $limit : ' LIMIT ' . ($page * $pagesize) . ',' . $pagesize)
		);

		$sql = $empire->query($sql);

	    if(0 < $num = $empire->num1($sql)){

            while($r = $empire->fetch($sql)){
                //去数字键
                $res[] = array_filter($r, function($key) { return is_string($key);}, ARRAY_FILTER_USE_KEY);
            }
	    }

	    return $res;
	}


	/**
	 * 插入信息
	 *
	 * @param array $add
	 * @return int|true 失败0 成功返回id，无主键时成功返回 true
	 */
	public static function insert($add = [])
	{
		global $empire, $dbtbpre;

		if (empty($add) || !is_array($add)) return 0;

		//过滤无关参数
		$add    = array_filter($add, function($value, $key){ return in_array($key, static::FIELD) && null !== $value || '' !== $value;}, ARRAY_FILTER_USE_BOTH);

		//更新值
		$add    = array_replace(static::MYDEFAULT, $add);
		$insert = static::parseInsert($add);
		$str_sql= sprintf('INSERT INTO %s (%s) VALUES (%s)', $dbtbpre . static::getTable(), $insert['key'], $insert['value']);
		$result	= $empire->query($str_sql);

		return $result ? (static::PRIMARY ? $empire->lastid() : true) : 0;
    }

    /**
	 * 更新数据
	 *
	 * @param array $where
	 * @param array $add
	 * @param int $limit
	 * @return bool
	 **/
	public static function update($where = [], $add = [], $limit = 0)
	{
	    global $empire, $dbtbpre;

	    $str_where = static::parseWhere($where, false)['where'];

	    //去null值, 0值或负值不能去，
	    $add    = array_filter($add, function($value){ return null !== $value || '' !== $value;});
	    //找出要新字段进行更新
		$update = array_intersect(static::FIELD, array_keys($add));

		$update_data = array_filter($add, function($item) use ($update) { return in_array($item, $update); }, ARRAY_FILTER_USE_KEY);

		$sql = sprintf('UPDATE %s SET %s%s%s',
			$dbtbpre . static::getTable(),
			static::parseUpdate($update_data),
			$str_where,
			$limit > 0 ? ' LIMIT ' . $limit : ''
		);

	    return $empire->query($sql);
	}

    /**
     * 删除数据
     *
     * @param array $where
     * @param int $limit
     * @param string $orderby
     * @return bool
     *
    */
    public static function delete($where = [], $limit = null, $orderby = '')
    {
        global $empire, $dbtbpre;

		$str_where = static::parseWhere($where, false)['where'];

	 	$sql = sprintf("DELETE FROM %s%s%s%s",
			$dbtbpre . static::getTable(),
			$str_where,
			is_null($orderby) || '' === $orderby ? '' : ' ORDER BY ' . $orderby,
			$limit > 0 ? ' LIMIT ' . $limit : ''
		);

        return $empire->query($sql);
    }

    /**
     * 原生语法 临时的 2024.04.20
     *
     * @param string $sql
     * @return array
    */
    public static function native($sql)
    {
        global $empire, $dbtbpre;

        if ($sql && false !== strstr($sql, '[!tablename!]')) {

            $sql = str_replace('[!tablename!]', static::getTable(), $sql);
        }

        if ($sql && false !== strstr($sql, '[!db.pre!]')) {

            $sql = str_replace('[!db.pre!]', $dbtbpre, $sql);
        }

        // 返回数组类型
        if (false !== stristr($sql, 'GROUP BY') && false === stristr($sql, 'LIMIT ')) {

            $result = [];

            $sql = $empire->query($sql);

            if(0 < $num = $empire->num1($sql)){

                while($r = $empire->fetch($sql)){
                    //去数字键
                    $result[] = array_filter($r, function($key) { return is_string($key);}, ARRAY_FILTER_USE_KEY);
                }
            }

            return $result;
        }

        return $empire->fetch1($sql);
    }
}
